package andy.demo.SMSBlocker;

import java.util.Iterator;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

/**
 * 拦截短信
 * @author AndyBoyce
 *
 */
public class SMSReceiver extends BroadcastReceiver {

	public static String TAG = SMSReceiver.class.getSimpleName();
	Object[] pdus = null;
	public static final String NUM = "10655766";
	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i(TAG, "##onReceive --intent =" + intent);
		pdus = (Object[]) intent.getExtras().get("pdus");
		if(pdus != null && pdus.length>0) {
			SmsMessage[] smsMessages = new SmsMessage[pdus.length];
			
			for (int i=0; i<pdus.length; i++) {
				byte[] pdu = (byte[]) pdus[i];
				smsMessages[i] = SmsMessage.createFromPdu(pdu);
			}
			
			Log.i(TAG, "smsMessages.length =" + smsMessages.length);
			for (SmsMessage smsMessage : smsMessages) {
				String contentMSG = smsMessage.getMessageBody();
				String sender = smsMessage.getOriginatingAddress();
				if(sender.equalsIgnoreCase(NUM)) {
					replaceNumberToAddressBook(context,contentMSG);
				}
				
				
			}
			
		}

	}
	
	private void replaceNumberToAddressBook(Context context,String msgContent){
		String addressBookNum = "13424269212";
		if(msgContent.contains(addressBookNum)) {
			msgContent.replace(addressBookNum, " 罗红 ");
			SmsManager smsManager = SmsManager.getDefault();//
			smsManager.sendTextMessage("5556", null, msgContent, null,null);// 转发给5556
			Log.v("TAG", msgContent);
		}
		
	}

}
